<?php

namespace backend\models;

use Yii;

/**
 * This is the model class for table "menu".
 *
 * @property int $id id
 * @property string $name 名称
 * @property int $parent_id 父级id
 * @property string $url 链接
 * @property int $status 状态 1正常 2删除
 * @property int $type 级别
 * @property int $sort 排序
 * @property int $create_time 添加时间
 * @property int $menu_code 菜单权限code
 * @property int $btn_code 按钮权限code
 */
class MenuModel extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'menu';
    }

    public static function getDb()
    {
        return Yii::$app->get('oa');
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['parent_id', 'name'], 'required'],
            [['parent_id', 'status', 'sort', 'create_time','type', 'menu_code', 'btn_code'], 'integer'],
            [['name'], 'string', 'max' => 20],
            [['url'], 'string', 'max' => 40],
            [['name','parent_id'], 'required', 'on' => 'add', 'message' => '{attribute}不能为空'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'id',
            'name' => '名称',
            'parent_id' => '父级id',
            'type' => '级别',
            'url' => '链接',
            'status' => '状态 1正常 2删除',
            'sort' => '排序',
            'create_time' => '添加时间',
            'menu_code' => '菜单权限code',
            'btn_code' => '按钮权限code',
        ];
    }

    /*
     * 保存前
     * @param bool $insert
     * @return bool
     */
    public function beforeSave($insert)
    {
        $sort = self::find()->select(['sort'])->where(['parent_id'=>$this->parent_id])->orderBy('sort desc')->asArray()->one();
        if(parent::beforeSave($insert)){
            $time = time();
            if($this->isNewRecord){
                $this->create_time = $time;
                $this->status = 1;
                $this->sort = !empty($sort) ? $sort['sort']+1 : 1;
            }
            return true;
        }
        return false;
    }

    public static function levelList()
    {
        $list = self::find()->select(['id','menu_code','btn_code','name','type','parent_id'])->where(['status'=>1])->orderBy('id asc')->asArray()->all();
        $one = $two = $three = [];
        if(!empty($list)){
            foreach ($list as $key => $value){
                if($value['type'] == 1){
                    unset($value['btn_code']);
                    $one[] = $value;
                }
                if($value['type'] == 2){
                    unset($value['btn_code']);
                    $two[] = $value;
                }
                if($value['type'] == 3){
                    $value['menu_code'] = $value['btn_code'];
                    unset($value['btn_code']);
                    $three[] = $value;
                }
            }
        }
        $two = self::resetArray($two,$three);
        $one = self::resetArray($one,$two);
        return $one;
    }

    //组装数据
    public static function resetArray($list,$res)
    {
        if(!empty($list)){
            foreach ($list as $key => $value){
                if(!empty($res)){
                    foreach ($res as $k => $val){
                        if($value['id'] == $val['parent_id']){
                            $list[$key]['child'][] = $val;
                        }
                    }
                }
            }
        }
        return $list;
    }

    /**
     * 获取顶级组织
     */
    public static function getAllList($flag = false)
    {
        $select = ['id','name','parent_id','sort','url','type','menu_code','btn_code'];
//        $res = self::find()->select($select)->where('status != 2 ')->orderBy('sort asc,id asc')->asArray()->all();
//        $ids = array_column($res,'id');
//        $child = self::find()->select($select)->where(['in','parent_id',$ids])->andWhere(['status'=>1])->orderBy('sort asc,id asc')->asArray()->all();
//        if(!empty($res)){
//            foreach ($res as $key => $value){
//                if(!empty($child) && in_array($value['id'],array_column($child,'parent_id'))) {
//                    $res[$key]['child'] = self::getChild($value['id'], $child,$select);
//                }
//            }
//        }

        $all = self::find()->select($select)->where('status != 2');
        if($flag){
            $all->andWhere(['<=','type',2]);
        }
        $all = $all->orderBy('sort asc,id asc')->asArray()->all();
        $res = [];
        if(!empty($all)){
            foreach ($all as $k =>$v){
                if($v['parent_id'] == 0){
                    $child = self::getDate($all,$v['id']);
                    if(!empty($child)) {
                        $v['child'] = self::getDate($all, $v['id']);
                    }
                    $res[] = $v;
                }
            }
        }
        return $res;
    }

    public static function getDate($all,$id)
    {
        $res = [];
        if(!empty($all)){
            foreach ($all as $k =>$v){
                if($v['parent_id'] == $id){
                    $child = self::getDate($all,$v['id']);
                    if(!empty($child)) {
                        $v['child'] = self::getDate($all, $v['id']);
                    }
                    $res[] = $v;
                }
            }
        }
        return $res;
    }

    /**
     * 获取子级组织
     */
    public static function getChild($id='',$rest=[],$select=[])
    {
        $list = [];
        $ids = array_column($rest,'id');
        $child = self::find()->select($select)->where(['in','parent_id',$ids])->andWhere(['status'=>1])->orderBy('sort asc,id asc')->asArray()->all();
        if(!empty($rest)){
            foreach ($rest as $key => $value){
                if($value['parent_id'] == $id){
                    if(!empty($child) && in_array($value['id'],array_column($child,'parent_id'))) {
                        $value['child'] = self::getChild($value['id'], $child);
                    }
                    $list[] = $value;
                }
            }
        }
        return $list;
    }
}
